package cn.demomaster.quickui_sample.ui.fragment.helper;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.demomaster.quickcompat.util.QuickThread;
import com.demomaster.quickcompat.widget.button.QuickButton;
import com.demomaster.quickcompat.widget.toast.QdToast;

import java.net.Socket;

import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quickrouter.fragment.QuickFragment;
import cn.demomaster.quickui.annotation.ActivityPager;
import cn.demomaster.quickui.annotation.ResType;
import cn.demomaster.quickui.helper.QuickNotification;
import cn.demomaster.quickui.network.NetworkWatcher;
import com.squirrelhuan.quickhttp.tcp.QuickTcpClient;
import com.squirrelhuan.quickhttp.tcp.QuickTcpServer;
import com.squirrelhuan.quickhttp.tcp.ReceiveListener;
import cn.demomaster.quickui_sample.R;


/**
 * Squirrel桓
 * 2018/8/25
 */

@ActivityPager(name = "Socket", preViewClass = TextView.class, resType = ResType.Custome)
public class SocketFragment extends QuickFragment implements ReceiveListener {

    QuickButton btn_send_tcp;
    QuickButton btn_send_tcp2;
    QuickButton btn_send_connect;
    QuickButton btn_start_server;
    TextView tv_local_ip;
    TextView tv_sn;
    TextView tv_server_log;
    TextView tv_client_log;
    EditText et_input, et_input2;
    EditText et_ip;

    View mView;

    @Override
    public View onGenerateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_layout_socket, null);
        }
        return mView;
    }

    QuickTcpServer qdTcpServer;
    QuickTcpClient qdTcpClient;
    int port = 6032;
    String clientID;
    String localIP;
    String targetServerIP;
    RadioGroup rg_client_type;
    Long clientId;

    public void initView(View rootView) {
        rg_client_type = findViewById(R.id.rg_client_type);
        rg_client_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_server) {
                    findViewById(R.id.ll_content_01).setVisibility(View.VISIBLE);
                    findViewById(R.id.ll_content_02).setVisibility(View.GONE);
                } else if (checkedId == R.id.rb_client) {
                    findViewById(R.id.ll_content_02).setVisibility(View.VISIBLE);
                    findViewById(R.id.ll_content_01).setVisibility(View.GONE);
                }
            }
        });
        btn_send_tcp = findViewById(R.id.btn_send_tcp);
        btn_send_tcp2 = findViewById(R.id.btn_send_tcp2);
        btn_send_connect = findViewById(R.id.btn_send_connect);
        btn_start_server = findViewById(R.id.btn_start_server);
        tv_local_ip = findViewById(R.id.tv_local_ip);
        tv_sn = findViewById(R.id.tv_sn);
        tv_server_log = findViewById(R.id.tv_server_log);
        tv_client_log = findViewById(R.id.tv_client_log);
        et_input = findViewById(R.id.et_input);
        et_input2 = findViewById(R.id.et_input2);
        et_ip = findViewById(R.id.et_ip);
        getActionBarTool().setTitle("socket");

        //clientID = QDAndroidDeviceUtil.getUniqueID(getContext());
        tv_sn.setText(clientID);
        localIP = NetworkWatcher.getLocalIpAddress(mContext);
        targetServerIP = localIP;
        tv_local_ip.setText(localIP);
        et_ip.setText(targetServerIP);
        btn_start_server.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (qdTcpServer == null) {
                    qdTcpServer = new QuickTcpServer(localIP, port);//
                    qdTcpServer.setOnReceiveMessageListener(new QuickTcpServer.OnReceiveListener() {
                        @Override
                        public void onClientConnect(Socket socket) {
                            clientId = qdTcpServer.getClientIdBySocket(socket);
                            QuickNotification.Builer builer = new QuickNotification.Builer(mContext);
                            builer.setTitle("消息通知")
                                    .setContentText("收到socket消息")
                                    .send();
                            QuickThread.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv_server_log.append("客户端连接" + socket + "\n");
                                }
                            });
                        }

                        @Override
                        public void onReceiveMessage(Socket socket, byte[] bytes) {
                            QuickThread.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv_server_log.append(new String(bytes) + "\n");
                                }
                            });
                        }
                    });
                }
                qdTcpServer.start();
                //port = qdTcpServer.getPort();
                //qdTcpClient.setPort(port);
                //QdToast.show(getContext(),"port:"+port);// new QDTcpServer(port);
            }
        });
        btn_send_connect.setOnClickListener(v -> {
            if (et_ip.getText() != null) {
                targetServerIP = et_ip.getText().toString();
            }
            QdLog.println("btn_send_connect " + targetServerIP);
            qdTcpClient = new QuickTcpClient(targetServerIP, port);
            qdTcpClient.setReceiveListener(this);
            qdTcpClient.connect();
        });

        btn_send_tcp.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(et_input.getText()) && qdTcpClient != null) {
                String str = et_input.getText().toString();
                qdTcpClient.sendBytes(str.getBytes());
            }
        });
        btn_send_tcp2.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(et_input2.getText()) && qdTcpServer != null) {
                String str = et_input2.getText().toString();
                qdTcpServer.sendMessage(clientId, System.currentTimeMillis(), str);
            }
        });
        //QDTcpClient.setStateListener();
        rg_client_type.check(R.id.rb_server);
    }

    private void initTCPMessage() {
        QdToast.show(getContext(), "连接成功");
        /*QDTcpClient.getInstance().request(JSON.toJSONString(connectInfo), new RequestListener() {
            @Override
            public void onReceived(QDMessage qdMessage, byte[] bytes) {

            }

            @Override
            public void onError(String err) {

            }
        });*/
    }

    @Override
    public void onConnect() {
        initTCPMessage();
    }

    @Override
    public void onReceived(byte[] bytes) {
        tv_client_log.append(new String(bytes) + "\n");
    }

    @Override
    public void onLostConnect(int failCode, String msg) {

    }

   /* public void initActionBarLayout(ActionBarLayout2 actionBarLayoutOld) {
        int i = (int) (Math.random() * 10 % 4);
        actionBarLayoutOld.setTitle("audio play");
        actionBarLayoutOld.setHeaderBackgroundColor(Color.RED);

    }*/
}